<?php
declare(strict_types=1);

namespace Reven\RevenHyperfValidator;

use \Reven\Result\Re;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\ApplicationContext;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

class Validate
{
    public static function httpValidate(RequestInterface $request, array $rules, array $messages = [], array $customAttributes = []):Re {
        return self::validate($request->all(),$rules,$messages,$customAttributes);
    }

    public static function validate(array $params,array $rules,array $messages=[], array $customAttributes = []):Re{
        $validator=self::getValidationFactory()->make($params,$rules,$messages,$customAttributes);
        if ($validator->fails()){
            $errors = $validator->errors();
            // 构建错误详情数组，便于后续处理或展示
            $errorMessages = [];
            foreach ($errors->toArray() as $field => $messagesForField) {
                foreach ($messagesForField as $message) {
                    $errorMessages[] = $field.":".$message;
                }
            }
            return new Re(false,implode(';',$errorMessages),$params);
        }
        return new Re(true,"",$params);
    }

    private static function getValidationFactory():ValidatorFactoryInterface{
        return ApplicationContext::getContainer()->get(ValidatorFactoryInterface::class);
    }
}